import React, { useEffect, useState, useRef } from "react";
import {
  PageHeader,
  Steps,
  Button,
  Form,
  Input,
  Select,
  message,
  notification
} from "antd";
import NewsEditor from "../../../components/news-manage/NewsEditor";
import style from "./NewsAdd.module.scss";
import axios from "axios";

const { Step } = Steps;
const { Option } = Select;

export default function NewsUpdate(props) {
  const [step, setStep] = useState(0);
  const [categories, setCategories] = useState([]);
  const [newBaseInfo, setNewBaseInfo] = useState({});
  const [content, setContent] = useState("");
  const newFormRef = useRef(null);
  useEffect(() => {
    axios.get("/categories").then(({ data }) => {
      setCategories(data);
    });
  }, []);
  useEffect(() => {
    axios
      .get(`/news/${props.match.params.id}?_expand=categoty`)
      .then(({ data }) => {
        const { title, categoryId, content } = data;
        newFormRef.current.setFieldsValue({
          title,
          categoryId
        });
        setContent(content);
      });
  }, [props.match.params.id]);
  const handleNext = () => {
    if (step === 0) {
      newFormRef.current
        .validateFields()
        .then(values => {
          setNewBaseInfo(values);
          setStep(step + 1);
        })
        .catch(err => {
          console.log(err);
        });
    } else {
      if (content === "" || content.trim() === "<p></p>") {
        message.error("新闻内容不能为空！");
      } else {
        setStep(step + 1);
      }
    }
  };
  const handlePrevious = () => {
    setStep(step - 1);
  };
  const getEditContent = data => {
    setContent(data);
  };
  const save = auditState => {
    axios
      .patch(`/news/${props.match.params.id}`, {
        ...newBaseInfo,
        content: content,
        auditState: auditState
      })
      .then(() => {
        props.history.push(
          auditState === 0 ? "/news-manage/draft" : "/audit-manage/list"
        );
        notification.info({
          message: "通知",
          description: `您的新闻修改成功，已保存到${
            auditState === 0 ? "[草稿箱]" : "[审核列表]"
          }中`,
          placement: "bottomRight"
        });
      });
  };
  return (
    <div>
      <PageHeader
        onBack={() => window.history.back()}
        className="site-page-header"
        title="修改新闻"
        subTitle="update"
      />
      <Steps current={step}>
        <Step title="基本信息" description="新闻标题，新闻分类" />
        <Step title="新闻内容" description="新闻主体内容" />
        <Step title="新闻提交" description="保存草稿或者提交审核" />
      </Steps>
      <div className={style.body}>
        <div
          className={step === 0 ? "" : style.hide}
          style={{ minHeight: "115px" }}
        >
          <Form
            ref={newFormRef}
            name="basic"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
          >
            <Form.Item
              label="新闻标题"
              name="title"
              rules={[{ required: true, message: "Please input your title!" }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="新闻分类"
              name="categoryId"
              rules={[
                { required: true, message: "Please select your category!" }
              ]}
            >
              <Select>
                {categories.map(item => (
                  <Option value={item.id} key={item.id}>
                    {item.title}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Form>
        </div>
        <div className={step === 1 ? "" : style.hide}>
          <NewsEditor getEditContent={getEditContent} content={content} />
        </div>
        <div className={step === 2 ? "" : style.hide}></div>
      </div>
      <div className={style.footer}>
        {step === 2 && (
          <>
            <Button type="primary" onClick={() => save(0)}>
              保存草稿
            </Button>
            <Button type="danger" onClick={() => save(1)}>
              提交审核
            </Button>
          </>
        )}
        {step !== 2 && (
          <Button type="primary" onClick={handleNext}>
            下一步
          </Button>
        )}
        {step !== 0 && <Button onClick={handlePrevious}>上一步</Button>}
      </div>
    </div>
  );
}
